package com.jsh.erp.service.crk;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.Kucun;
import com.jsh.erp.datasource.entities.KucunExample;
import com.jsh.erp.datasource.entities.KucunRecord;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.KucunMapper;
import com.jsh.erp.datasource.mappers.KucunMapperEx;
import com.jsh.erp.datasource.mappers.KucunRecordMapper;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.BaseResponseInfo;
import com.jsh.erp.utils.ExcelUtils;
import com.jsh.erp.utils.StringUtil;
import jxl.Sheet;
import jxl.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@Service
public class KucunService {
    private Logger logger = LoggerFactory.getLogger(KucunService.class);

    @Resource
    private KucunMapper kucunMapper;
    @Resource
    private KucunRecordMapper kucunRecordMapper;
    @Resource
    private KucunMapperEx kucunMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;

    public Kucun getKucun(long id)throws Exception {
        Kucun result=null;
        try{
            result= kucunMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<Kucun> getKucunListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<Kucun> list = new ArrayList<>();
        try{
            KucunExample example = new KucunExample();
            example.createCriteria().andIdIn(idList);
            list = kucunMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Kucun> getKucun()throws Exception {
        KucunExample example = new KucunExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Kucun> list=null;
        try{
            list= kucunMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<Kucun> select(String name, String type, String remark, int offset, int rows)throws Exception {
        List<Kucun> list=null;
        try{
            list= kucunMapperEx.selectByConditionKucun(name, type, remark, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countKucun(String name, String type, String remark)throws Exception {
        Long result=null;
        try{
            result= kucunMapperEx.countsByKucun(name, type, remark);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertKucun(JSONObject obj, HttpServletRequest request)throws Exception {
        Kucun inOutItem = JSONObject.parseObject(obj.toJSONString(), Kucun.class);
        int result=0;
        try{
            inOutItem.setEnabled(true);
            result= kucunMapper.insertSelective(inOutItem);
            logService.insertLog("食谱管理",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(inOutItem.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    public int updateKucun(Kucun kucun)throws Exception {
        int result=0;
        try{
            result= kucunMapper.updateByPrimaryKeySelective(kucun);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteKucun(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteKucunByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteKucun(String ids, HttpServletRequest request)throws Exception {
        return batchDeleteKucunByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteKucunByIds(String ids)throws Exception {
        int result = 0;
        String [] idArray=ids.split(",");
        //校验通过执行删除操作
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<Kucun> list = getKucunListByIds(ids);
        for(Kucun inOutItem: list){
            sb.append("[").append(inOutItem.getName()).append("]");
        }
        logService.insertLog("食谱管理", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        User userInfo=userService.getCurrentUser();
        try{
            result= kucunMapperEx.batchDeleteKucunByIds(new Date(),userInfo==null?null:userInfo.getId(),idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        KucunExample example = new KucunExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Kucun> list = null;
        try{
            list= kucunMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }

        return list==null?0:list.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchSetStatus(Boolean status, String ids)throws Exception {
        logService.insertLog("食谱管理",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ENABLED).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        List<Long> inOutItemIds = StringUtil.strToLongList(ids);
        Kucun inOutItem = new Kucun();
        inOutItem.setEnabled(status);
        KucunExample example = new KucunExample();
        example.createCriteria().andIdIn(inOutItemIds);
        int result=0;
        try{
            result = kucunMapper.updateByExampleSelective(inOutItem, example);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void importKucun(MultipartFile file, HttpServletRequest request) throws Exception{
        String type = "采购入库";
        User userInfo = userService.getCurrentUser();
        Workbook workbook = Workbook.getWorkbook(file.getInputStream());
        Sheet src = workbook.getSheet(0);
        List<KucunRecord> sList = new ArrayList<>();
        for (int i = 2; i < src.getRows(); i++) {
            String xh = ExcelUtils.getContent(src, i, 0);
            String rkDate = ExcelUtils.getContent(src, i, 1);
            String name = ExcelUtils.getContent(src, i, 2);
            String amount = ExcelUtils.getContent(src, i, 3);
            String price = ExcelUtils.getContent(src, i, 4);
            String sumPrice = ExcelUtils.getContent(src, i, 5);
            String zl = ExcelUtils.getContent(src, i, 6);
            String remark = ExcelUtils.getContent(src, i, 7);
            if(StringUtil.isNotEmpty(name) && StringUtil.isNotEmpty(amount)) {
                KucunRecord kr = new KucunRecord();
                kr.setXh(xh);
                kr.setRkDate(rkDate);
                kr.setName(name);
                kr.setAmount(amount);
                kr.setPrice(price);
                kr.setSumPrice(sumPrice);
                kr.setZl(zl);
                kr.setRemark(remark);
                sList.add(kr);
            }
        }
        importExcel(sList, type, request);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public BaseResponseInfo importExcel(List<KucunRecord> mList, String type, HttpServletRequest request) throws Exception {
        logService.insertLog(type,
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        BaseResponseInfo info = new BaseResponseInfo();
        Map<String, Object> data = new HashMap<>();
        try {
            List<Kucun> kucunList = this.getKucun();
            for (int i = 0; i < mList.size(); i++) {
                KucunRecord record = mList.get(i);
                kucunRecordMapper.insertSelective(record);
                Optional<Kucun> optional = kucunList.stream().filter(e->e.getName().equalsIgnoreCase(record.getName())).findFirst();
                if(optional.isPresent()){
                    Kucun kucun = optional.get();
                    BigDecimal amount1 = new BigDecimal(kucun.getAmount());
                    BigDecimal amount2 = new BigDecimal(record.getAmount());
                    BigDecimal sumAmount = amount1.add(amount2);
                    kucun.setAmount(sumAmount.toString());
                    kucun.setSort(String.valueOf(i));
                    kucun.setEnabled(true);
                    kucunMapper.updateByPrimaryKey(kucun);
                }else{
                    Kucun kucun = new Kucun();
                    kucun.setName(record.getName());
                    kucun.setAmount(record.getAmount());
                    kucun.setSort(String.valueOf(i));
                    kucun.setEnabled(true);
                    kucunList.add(kucun);
                    kucunMapper.insertSelective(kucun);
                }
            }
            info.code = 200;
            data.put("message", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            info.code = 500;
            data.put("message", e.getMessage());
        }
        info.data = data;
        return info;
    }
}
